{% extends 'base.html' %}
{% load static %}

{% block title %}{{ activity.title }} - 活动详情{% endblock %}

{% block extra_css %}
<style>
    .activity-hero {
        position: relative;
        height: 450px;
        background-size: cover;
        background-position: center;
        border-radius: 1rem;
        overflow: hidden;
        margin-bottom: 2rem;
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        transition: transform 0.3s ease;
    }
    
    .activity-hero:hover {
        transform: translateY(-5px);
    }
    
    .activity-hero::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(to bottom, transparent, rgba(0,0,0,0.8));
    }
    
    .activity-hero-content {
        position: absolute;
        bottom: 2rem;
        left: 2rem;
        right: 2rem;
        color: white;
        z-index: 1;
        text-shadow: 0 2px 4px rgba(0,0,0,0.5);
    }
    
    .info-card {
        background: white;
        border-radius: 1rem;
        padding: 1.5rem;
        box-shadow: var(--shadow-md);
        position: sticky;
        top: 100px;
    }
    
    .info-item {
        display: flex;
        align-items: start;
        gap: 1rem;
        padding: 1rem 0;
        border-bottom: 1px solid var(--border-color);
    }
    
    .info-item:last-child {
        border-bottom: none;
    }
    
    .info-icon {
        width: 40px;
        height: 40px;
        background: var(--gradient-primary);
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        flex-shrink: 0;
    }
    
    /* 组织者卡片优化 */
    .organizer-card {
        display: flex;
        align-items: center;
        gap: 1.25rem;
        padding: 1.5rem;
        background: linear-gradient(135deg, rgba(255,255,255,1) 0%, rgba(248,250,252,1) 100%);
        border-radius: 1rem;
        margin-bottom: 1rem;
        box-shadow: 0 6px 20px rgba(0,0,0,0.05);
        transition: all 0.3s ease;
        border: 1px solid rgba(0,0,0,0.03);
    }
    
    .organizer-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 12px 30px rgba(0,0,0,0.1);
    }
    
    .user-avatar-lg {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        object-fit: cover;
        border: 3px solid white;
        box-shadow: 0 4px 10px rgba(0,0,0,0.1);
    }
    
    /* 评论区优化 */
    .comment-box {
        background-color: var(--white);
        padding: 1.5rem;
        border-radius: 1rem;
        margin-bottom: 1rem;
        border: 1px solid var(--border-color);
        transition: all 0.2s ease;
        box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    }
    
    .comment-box:hover {
        border-color: var(--primary-color);
        box-shadow: 0 4px 15px rgba(0,123,255,0.1);
        transform: translateY(-2px);
    }
    
    .comment-content {
        line-height: 1.6;
        color: var(--dark-text);
        margin-top: 0.75rem;
    }
    
    /* 评论输入框优化 */
    .comment-input-area {
        border-radius: 1rem;
        overflow: hidden;
        border: 1px solid var(--border-color);
        transition: all 0.3s ease;
    }
    
    .comment-input-area:focus-within {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 2px rgba(0,123,255,0.2);
    }
    
    .comment-input {
        border: none;
        border-radius: 1rem;
        transition: all 0.2s ease;
    }
    
    .comment-input:focus {
        box-shadow: none;
        border-color: transparent;
        outline: none;
    }
    
    .comment-item {
        padding: 1.5rem;
        border-bottom: 1px solid var(--border-color);
        transition: background-color 0.2s;
    }
    
    .comment-item:hover {
        background-color: var(--light-bg);
    }
    
    .comment-item:last-child {
        border-bottom: none;
    }
    
    .comment-header {
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 0.75rem;
    }
    
    .comment-author {
        font-weight: 600;
        color: var(--dark-text);
    }
    
    .comment-time {
        font-size: 0.85rem;
        color: var(--gray-text);
    }
    
    .comment-content {
        margin-left: 56px;
        color: var(--dark-text);
        line-height: 1.6;
    }
    
    /* 互动统计优化 */
    .like-btn {
        transition: all 0.2s ease;
    }
    
    .like-btn:hover {
        color: var(--primary-color);
        transform: scale(1.1);
    }
    
    .like-btn.liked {
        color: var(--danger-color);
    }
    
    .action-stats {
        display: flex;
        gap: 1.5rem;
        margin-top: 1.5rem;
        padding: 1.25rem;
        background: linear-gradient(135deg, rgba(248,249,250,1) 0%, rgba(241,243,245,1) 100%);
        border-radius: 1rem;
        border-left: 4px solid var(--primary-color);
        box-shadow: 0 3px 10px rgba(0,0,0,0.05);
    }
    
    .stat-item {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        cursor: pointer;
        transition: all 0.2s ease;
        padding: 0.6rem 1rem;
        border-radius: 0.75rem;
        font-weight: 500;
        color: var(--dark-text);
    }
    
    .stat-item:hover {
        color: var(--primary-color);
        transform: translateY(-2px);
        background-color: rgba(255,255,255,0.8);
        box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    }
    
    .stat-item.active {
        color: var(--primary-color);
        font-weight: 600;
        background-color: rgba(255,255,255,0.9);
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    
    /* 活动描述样式优化 */
    .activity-description {
        line-height: 1.8;
        color: var(--dark-text);
        text-align: justify;
        font-size: 1.05rem;
        white-space: pre-wrap;
    }
    
    /* 网格纹理样式 */
    .bg-grid-white {
        background-image: linear-gradient(to right, rgba(255,255,255,0.1) 1px, transparent 1px),
                          linear-gradient(to bottom, rgba(255,255,255,0.1) 1px, transparent 1px);
        background-size: 20px 20px;
    }
    
    /* 响应式设计优化 */
    @media (max-width: 992px) {
        .activity-info-grid {
            grid-template-columns: 1fr;
        }
        
        .activity-hero {
            height: 400px;
        }
    }
    
    @media (max-width: 768px) {
        .activity-hero .container {
            padding-left: 1rem;
            padding-right: 1rem;
        }
        
        .activity-hero-content {
            padding: 1.5rem;
            bottom: 1.5rem;
            left: 1.5rem;
            right: 1.5rem;
        }
        
        .activity-hero {
            height: 350px;
        }
        
        .activity-hero-content h1 {
            font-size: 2rem;
        }
        
        .action-buttons {
            flex-wrap: wrap;
        }
        
        .action-buttons .btn {
            flex-grow: 1;
            margin-bottom: 0.5rem;
        }
        
        .action-stats {
            gap: 1rem;
            flex-wrap: wrap;
        }
        
        .stat-item {
            flex: 1;
            justify-content: center;
        }
        
        .organizer-card {
            flex-direction: column;
            text-align: center;
        }
        
        .participants-list {
            grid-template-columns: 1fr;
        }
    }
    
    @media (max-width: 480px) {
        .activity-hero {
            height: 300px;
        }
        
        .activity-hero-content h1 {
            font-size: 1.75rem;
        }
        
        .detail-content .card {
            border-radius: 0.5rem;
        }
        
        .activity-hero-content {
            padding: 1rem;
            bottom: 1rem;
            left: 1rem;
            right: 1rem;
        }
    }
    
    /* 地图区域优化 */
    #map {
        height: 300px;
        border-radius: 1rem;
        overflow: hidden;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        border: 1px solid rgba(0,0,0,0.05);
    }
    
    /* 位置信息区域美化 */
    .location-info {
        background: linear-gradient(135deg, rgba(248,250,252,1) 0%, rgba(255,255,255,1) 100%);
        padding: 1rem;
        border-radius: 0.75rem;
        margin-bottom: 1rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        border-left: 4px solid var(--primary-color);
    }
    
    .location-info h6 {
        margin-bottom: 0.5rem;
        color: var(--primary-color);
        font-weight: 600;
    }
    
    .location-info p {
        margin-bottom: 0.25rem;
        line-height: 1.5;
    }
    
    /* 卡片样式增强 */
    .card-custom {
        border-radius: 1rem;
        overflow: hidden;
        border: none;
        box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        margin-bottom: 1.5rem;
    }
    
    .card-custom:hover {
        transform: translateY(-4px);
        box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1), 0 10px 10px -5px rgba(0,0,0,0.04);
    }
    
    .card-custom .card-header {
        background: linear-gradient(90deg, var(--primary-color), #64b5f6);
        color: white;
        border-bottom: none;
        padding: 1rem 1.25rem;
    }
    
    .card-custom .card-body {
        padding: 1.5rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-4">
    <!-- 美化后的活动封面 -->
    <div class="activity-hero rounded-lg overflow-hidden mb-6 relative" style="background-image: url('{{ activity.cover_image|default:'/static/img/default-activity.jpg' }}');">
        <!-- 装饰性元素 -->
        <div class="absolute top-0 left-0 w-full h-full opacity-30">
            <div class="absolute top-0 left-0 w-64 h-64 bg-primary/40 rounded-full -translate-x-1/2 -translate-y-1/2 blur-3xl"></div>
            <div class="absolute bottom-0 right-0 w-80 h-80 bg-secondary/40 rounded-full translate-x-1/3 translate-y-1/3 blur-3xl"></div>
            <!-- 网格纹理装饰 -->
            <div class="absolute inset-0 bg-grid-white/10"></div>
        </div>
        
        <div class="activity-hero-content">
            <!-- 顶部标签 -->
            <div class="flex flex-wrap align-items-center gap-2 mb-4">
                <span class="badge bg-white/90 text-dark font-medium px-4 py-1.5 rounded-full">
                    <i class="fas fa-tag me-1"></i>{{ activity.activity_type.name }}
                </span>
                {% if activity.is_free %}
                <span class="badge bg-emerald-500/90 text-white font-medium px-4 py-1.5 rounded-full">
                    <i class="fas fa-ticket-alt me-1"></i>免费
                </span>
                {% else %}
                <span class="badge bg-amber-500/90 text-white font-medium px-4 py-1.5 rounded-full">
                    <i class="fas fa-yen-sign me-1"></i>¥{{ activity.fee }}
                </span>
                {% endif %}
                
                <!-- 活动状态标签 -->
                {% if activity.status == 'published' %}
                <span class="badge bg-blue-500/90 text-white font-medium px-4 py-1.5 rounded-full">
                    <i class="fas fa-calendar-check me-1"></i>即将开始
                </span>
                {% elif activity.status == 'ongoing' %}
                <span class="badge bg-purple-500/90 text-white font-medium px-4 py-1.5 rounded-full">
                    <i class="fas fa-play-circle me-1"></i>进行中
                </span>
                {% elif activity.status == 'completed' %}
                <span class="badge bg-gray-500/90 text-white font-medium px-4 py-1.5 rounded-full">
                    <i class="fas fa-flag-checkered me-1"></i>已结束
                </span>
                {% endif %}
            </div>
            
            <!-- 活动标题 -->
            <h1 class="display-2 md:display-3 lg:display-4 fw-bold mb-4 leading-tight tracking-tight">{{ activity.title }}</h1>
            
            <!-- 创建者信息 -->
            <div class="flex items-center gap-3 mb-5 bg-black/20 backdrop-blur-sm p-2 rounded-lg inline-block">
                <img src="{{ activity.creator.avatar|default:'/static/img/default-avatar.png' }}" 
                     class="w-10 h-10 rounded-full border-2 border-white shadow-md" 
                     alt="创建者头像">
                <span class="text-white font-medium">{{ activity.creator.nickname }}</span>
                <span class="text-white/80 text-sm">创建于 {{ activity.created_at|date:"Y年m月d日" }}</span>
            </div>
            
            <!-- 活动简介 -->
            <div class="bg-black/30 backdrop-blur-md p-4 rounded-xl inline-block max-w-3xl">
                <p class="lead text-white/95 mb-0">{{ activity.description|truncatewords:30 }}</p>
            </div>
            
            <!-- 底部装饰元素 -->
            <div class="absolute bottom-0 left-0 w-full h-16 bg-gradient-to-t from-black/60 to-transparent"></div>
        </div>
    </div>
    
    <div class="row">
        <!-- 左侧内容 -->
        <div class="col-lg-8 mb-4">
            <!-- 活动详情 -->
            <div class="card card-custom mb-4 transform transition-all duration-300 hover:shadow-lg">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-info-circle"></i> 活动详情</h5>
                </div>
                <div class="card-body">
                    <div class="activity-description p-4 bg-gradient-to-br from-gray-50 to-white rounded-xl border border-gray-100">
                        {{ activity.description|linebreaks }}
                    </div>
                    
                    <!-- 美化的互动统计 -->
                <div class="action-stats">
                    <div class="stat-item" id="likeBtn" onclick="toggleLike()">
                        <i class="far fa-heart fa-lg" id="likeIcon"></i>
                        <div>
                            <span id="likeCount">{{ activity.like_count|default:0 }}</span>
                            <span class="text-sm d-block">点赞</span>
                        </div>
                    </div>
                    <div class="stat-item">
                        <i class="far fa-comment fa-lg"></i>
                        <div>
                            <span id="commentCountStat">{{ activity.comment_count|default:0 }}</span>
                            <span class="text-sm d-block">评论</span>
                        </div>
                    </div>
                    <div class="stat-item">
                        <i class="far fa-eye fa-lg"></i>
                        <div>
                            <span>{{ activity.view_count }}</span>
                            <span class="text-sm d-block">浏览</span>
                        </div>
                    </div>
                    <div class="stat-item" onclick="shareActivity()">
                        <i class="fas fa-share-alt fa-lg"></i>
                        <div>
                            <span>分享</span>
                            <span class="text-sm d-block">传播</span>
                        </div>
                    </div>
                </div>
                </div>
            </div>
            
            <!-- 组织者信息 -->
            <div class="card card-custom mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-user-tie"></i> 组织者</h5>
                </div>
                <div class="card-body">
                    <div class="organizer-card">
                        <img src="{{ activity.creator.avatar|default:'/static/img/default-avatar.png' }}" 
                             class="user-avatar-lg" 
                             alt="{{ activity.creator.nickname }}的头像">
                        <div class="flex-grow-1">
                            <div class="flex items-center gap-2 mb-1">
                                <h5 class="mb-0 font-semibold">{{ activity.creator.nickname }}</h5>
                                <span class="badge bg-primary/10 text-primary text-xs px-2 py-0.5 rounded-full">活动组织者</span>
                            </div>
                            <p class="text-gray-500 text-sm mb-2">已创建 <span class="font-medium text-primary">{{ activity.creator.created_activities_count }}</span> 个精彩活动</p>
                            {% if activity.creator.signature %}
                            <p class="mb-0 text-gray-600 italic">
                                <i class="fas fa-quote-left text-gray-400"></i> {{ activity.creator.signature }}
                            </p>
                            {% endif %}
                        </div>
                        <a href="{% url 'users:profile' activity.creator.id %}" 
                           class="btn btn-primary rounded-lg px-4 py-2 hover:bg-primary/90 transition-colors duration-200">
                            <i class="fas fa-user-circle me-1"></i> 查看主页
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- 地图位置 -->
            <div class="card card-custom mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-map-marker-alt"></i> 活动地点</h5>
                </div>
                <div class="card-body">
                    <div class="location-info">
                        <h6><i class="fas fa-map-marker-alt me-2"></i>{{ activity.location_name }}</h6>
                        <p class="text-muted mb-0">{{ activity.location_address }}</p>
                    </div>
                    <div id="map"></div>
                </div>
            </div>
            
            <!-- 美化的参与者列表 -->
            <div class="card mb-5 rounded-xl overflow-hidden shadow-md">
                <div class="card-header bg-gradient-to-r from-primary/5 to-primary/10 px-6 py-4">
                    <h5 class="mb-0 font-semibold text-primary"><i class="fas fa-users"></i> 参与者 <span class="text-gray-600">({{ activity.current_participants }}/{{ activity.max_participants }})</span></h5>
                </div>
                <div class="card-body p-6">
                    <div id="participantsContainer" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        <div class="text-center"><div class="loader"></div></div>
                    </div>
                </div>
            </div>
            
            <!-- 美化的评论区 -->
            <div class="card mb-5 rounded-xl overflow-hidden shadow-md">
                <div class="card-header bg-gradient-to-r from-primary/5 to-primary/10 px-6 py-4">
                    <h5 class="mb-0 font-semibold text-primary"><i class="fas fa-comments"></i> 评论 <span class="text-gray-600">(<span id="commentCount">0</span>)</span></h5>
                </div>
                <div class="card-body p-6">
                    <!-- 评论输入 -->
                    {% if user.is_authenticated %}
                    <div class="comment-form mb-6">
                        <div class="comment-input-area">
                            <div class="input-group">
                                <textarea class="form-control comment-input py-3 px-4" id="commentInput" rows="3" 
                                       placeholder="分享你的想法和建议..."></textarea>
                                <button class="btn btn-primary rounded-r-lg px-5 mt-3" onclick="submitComment()">
                                    <i class="fas fa-paper-plane mr-2"></i> 发表
                                </button>
                            </div>
                        </div>
                    </div>
                    {% else %}
                    <p class="text-muted mb-4 text-center py-4 bg-gray-50 rounded-lg">
                        请先 <a href="{% url 'users:login' %}?next={{ request.path }}" class="text-primary hover:underline">登录</a> 后发表评论
                    </p>
                    {% endif %}
                    
                    <!-- 评论列表 -->
                    <div id="commentsContainer">
                        <p class="text-center text-muted py-8 bg-gray-50 rounded-lg">
                            <i class="far fa-comment-dots text-2xl text-gray-300 mb-2 block"></i>
                            暂无评论，快来发表第一条评论吧！
                        </p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 右侧信息栏 -->
        <div class="col-lg-4">
            <div class="info-card">
                <!-- 活动状态 -->
                <div class="text-center mb-3" id="activityStatus">
                    {% if activity.status == 'published' %}
                    <div class="alert alert-success mb-3">
                        <i class="fas fa-check-circle"></i> 可以报名
                    </div>
                    {% elif activity.status == 'ongoing' %}
                    <div class="alert alert-primary mb-3">
                        <i class="fas fa-play-circle"></i> 活动进行中
                    </div>
                    {% elif activity.status == 'completed' %}
                    <div class="alert alert-secondary mb-3">
                        <i class="fas fa-flag-checkered"></i> 活动已结束
                    </div>
                    {% endif %}
                </div>
                
                <!-- 美化的活动信息 -->
                <div class="info-item">
                    <div class="info-icon bg-blue-500"><i class="fas fa-calendar-alt"></i></div>
                    <div>
                        <small class="text-gray-500 font-medium">开始时间</small>
                        <div class="fw-bold text-gray-800">{{ activity.start_time|date:"Y年m月d日 H:i" }}</div>
                    </div>
                </div>
                
                <div class="info-item">
                    <div class="info-icon bg-purple-500"><i class="fas fa-clock"></i></div>
                    <div>
                        <small class="text-gray-500 font-medium">结束时间</small>
                        <div class="fw-bold text-gray-800">{{ activity.end_time|date:"Y年m月d日 H:i" }}</div>
                    </div>
                </div>
                
                <div class="info-item">
                    <div class="info-icon bg-green-500"><i class="fas fa-map-marker-alt"></i></div>
                    <div>
                        <small class="text-gray-500 font-medium">活动地点</small>
                        <div class="fw-bold text-gray-800">{{ activity.location_name|truncatechars:15 }}</div>
                        <small class="text-gray-500">{{ activity.location_address|truncatechars:20 }}</small>
                    </div>
                </div>
                
                <div class="info-item">
                    <div class="info-icon bg-green-500"><i class="fas fa-users"></i></div>
                    <div>
                        <small class="text-gray-500 font-medium">参与人数</small>
                        <div class="fw-bold text-gray-800">{{ activity.current_participants }}/{{ activity.max_participants }}</div>
                        <div class="progress mt-2" style="height: 8px; border-radius: 4px; overflow: hidden;">
                            <div class="progress-bar bg-gradient-to-r from-green-400 to-emerald-500" 
                                 style="width: {% widthratio activity.current_participants activity.max_participants 100 %}%;"
                                 role="progressbar"></div>
                        </div>
                    </div>
                </div>
                
                {% if not activity.is_free %}
                <div class="info-item">
                    <div class="info-icon bg-amber-500"><i class="fas fa-yen-sign"></i></div>
                    <div>
                        <small class="text-gray-500 font-medium">活动费用</small>
                        <div class="fw-bold text-amber-600 text-xl">¥{{ activity.fee }}</div>
                    </div>
                </div>
                {% endif %}
                
                <div class="info-item">
                    <div class="info-icon bg-gray-500"><i class="fas fa-eye"></i></div>
                    <div>
                        <small class="text-gray-500 font-medium">浏览次数</small>
                        <div class="fw-bold text-gray-800">{{ activity.view_count }}</div>
                    </div>
                </div>
                
                <!-- 美化的操作按钮 -->
                <div class="d-grid gap-3 mt-5" id="actionButtons">
                    {% if user.is_authenticated %}
                        {% if user.id == activity.creator.id %}
                        <a href="{% url 'activities:edit' activity.id %}" class="btn btn-primary btn-lg py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300">
                            <i class="fas fa-edit me-2"></i> 编辑活动
                        </a>
                        {% else %}
                        <button class="btn bg-gradient-to-r from-emerald-500 to-teal-600 text-white btn-lg py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300" 
                                id="registerBtn" onclick="registerActivity()">
                            <i class="fas fa-hand-paper me-2"></i> 立即报名
                        </button>
                        {% endif %}
                        
                        <div class="d-flex gap-3">
                            <button class="btn btn-outline-primary flex-1 py-3 rounded-xl hover:bg-primary/5 transition-all duration-200" 
                                    onclick="shareActivity()">
                                <i class="fas fa-share-alt me-2"></i> 分享
                            </button>
                            <button class="btn btn-outline-secondary flex-1 py-3 rounded-xl hover:bg-gray-100 transition-all duration-200" 
                                    onclick="collectActivity()">
                                <i class="far fa-bookmark me-2"></i> 收藏
                            </button>
                        </div>
                    {% else %}
                    <a href="{% url 'users:login' %}?next={{ request.path }}" class="btn bg-gradient-to-r from-primary to-blue-600 text-white btn-lg py-3 rounded-xl shadow-lg hover:shadow-xl transition-all duration-300">
                        <i class="fas fa-sign-in-alt me-2"></i> 登录后报名
                    </a>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 报名表单模态框 -->
<div class="modal fade" id="registerModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">活动报名</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label-custom">报名备注</label>
                    <textarea class="form-control form-control-custom" id="registrationNote" rows="3" placeholder="有什么想对组织者说的吗？（选填）"></textarea>
                </div>
                
                {% if not activity.is_free %}
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i> 此活动需要支付 <strong>¥{{ activity.fee }}</strong>
                </div>
                {% endif %}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-gradient-success" onclick="confirmRegistration()">确认报名</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 活动数据配置（避免重复声明）
    var ACTIVITY_DATA = {
        id: {{ activity.id }},
        latitude: {{ activity.latitude|default:"0" }},
        longitude: {{ activity.longitude|default:"0" }},
        locationName: '{{ activity.location_name|escapejs }}',
        locationAddress: '{{ activity.location_address|escapejs }}',
        startTime: '{{ activity.start_time|date:"Y-m-d H:i" }}'
    };
    
    function initMap() {
        var mapElement = document.getElementById('map');
        if (!mapElement) return;
        
        // 使用全局配置的经纬度
        if (ACTIVITY_DATA.latitude == 0 || ACTIVITY_DATA.longitude == 0) {
            mapElement.innerHTML = '<div class="text-center py-5 bg-light rounded">' +
                '<i class="fas fa-map-marked-alt fa-3x text-muted mb-2"></i>' +
                '<p class="text-muted">暂无位置信息</p>' +
                '</div>';
            return;
        }
        
        // 初始化高德地图
        var map = new AMap.Map('map', {
            zoom: 15,
            center: [ACTIVITY_DATA.longitude, ACTIVITY_DATA.latitude],
            resizeEnable: true
        });
        
        // 添加标记（使用更小的自定义标记）
        var marker = new AMap.Marker({
            position: [ACTIVITY_DATA.longitude, ACTIVITY_DATA.latitude],
            map: map,
            title: ACTIVITY_DATA.locationName,
            offset: new AMap.Pixel(-10, -10), // 调整偏移量
            content: '<div style="width: 20px; height: 20px; background-color: #1890ff; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 12px; box-shadow: 0 2px 6px rgba(0,0,0,0.3);">📍</div>'
        });
        
        // 添加信息窗口
        var infoWindow = new AMap.InfoWindow({
            content: '<div class="p-2">' +
                '<h6>' + ACTIVITY_DATA.locationName + '</h6>' +
                '<p class="mb-1 text-muted">' + ACTIVITY_DATA.locationAddress + '</p>' +
                '<small class="text-primary">' + ACTIVITY_DATA.startTime + '</small>' +
                '</div>',
            offset: new AMap.Pixel(0, -30)
        });
        
        // 点击标记显示信息窗口
        marker.on('click', function() {
            infoWindow.open(map, marker.getPosition());
        });
        
        // 添加地图控件
        map.addControl(new AMap.ToolBar());
        map.addControl(new AMap.Scale());
        
        // 添加路线规划按钮
        var routeBtn = document.createElement('div');
        routeBtn.innerHTML = '<button class="btn btn-sm btn-primary mt-2" onclick="showRoute()">' +
            '<i class="fas fa-route"></i> 路线规划' +
            '</button>';
        mapElement.parentNode.appendChild(routeBtn);
    }
    
    // 路线规划
    function showRoute() {
        if (!navigator.geolocation) {
            showError('您的浏览器不支持地理位置获取');
            // 备用方案：直接打开地图
            var url = 'https://uri.amap.com/marker?position=' + ACTIVITY_DATA.longitude + ',' + ACTIVITY_DATA.latitude + 
                      '&name=' + encodeURIComponent(ACTIVITY_DATA.locationName);
            window.open(url, '_blank');
            return;
        }
        
        showLoading('获取您的位置中...');
        
        // 添加超时保护（8秒后强制打开备用方案）
        var timeoutId = setTimeout(function() {
            hideLoading();
            showError('定位超时，直接打开地图');
            var url = 'https://uri.amap.com/marker?position=' + ACTIVITY_DATA.longitude + ',' + ACTIVITY_DATA.latitude + 
                      '&name=' + encodeURIComponent(ACTIVITY_DATA.locationName);
            window.open(url, '_blank');
        }, 8000);
        
        navigator.geolocation.getCurrentPosition(
            function(position) {
                clearTimeout(timeoutId);
                var userLat = position.coords.latitude;
                var userLng = position.coords.longitude;
                
                // 使用高德地图路径规划
                var url = 'https://uri.amap.com/navigation?from=' + userLng + ',' + userLat + 
                         '&to=' + ACTIVITY_DATA.longitude + ',' + ACTIVITY_DATA.latitude + 
                         '&mode=bus&callnative=1';
                window.open(url, '_blank');
                
                hideLoading();
            },
            function(error) {
                clearTimeout(timeoutId);
                hideLoading();
                showError('获取位置失败：' + error.message);
                
                // 备用方案：直接打开地图
                var url = 'https://uri.amap.com/marker?position=' + ACTIVITY_DATA.longitude + ',' + ACTIVITY_DATA.latitude + 
                          '&name=' + encodeURIComponent(ACTIVITY_DATA.locationName);
                window.open(url, '_blank');
            },
            {
                enableHighAccuracy: false,  // 提高响应速度
                timeout: 5000,              // 5秒超时
                maximumAge: 30000           // 允许使用缓存
            }
        );
    }
    
    // 在页面加载时初始化地图
    document.addEventListener('DOMContentLoaded', function() {
        // 延迟加载地图，确保高德地图API已加载
        setTimeout(initMap, 500);
    });

    // 活动ID（用于点赞和评论）
    var activityId = ACTIVITY_DATA.id;
    let isLiked = false;
    
    // 页面加载时记录浏览
    document.addEventListener('DOMContentLoaded', function() {
        {% if user.is_authenticated %}
        API.recommendations.recordView(activityId, {
            source: 'direct',
            device_type: /Mobile/.test(navigator.userAgent) ? 'mobile' : 'desktop'
        }).catch(err => console.error('记录浏览失败:', err));
        
        // 检查点赞状态
        checkLikeStatus();
        {% endif %}
        
        loadParticipants();
        loadComments();
        checkRegistrationStatus();
    });
    
    // 检查点赞状态
    function checkLikeStatus() {
        axios.get(`/social/api/activities/${activityId}/like-status/`)
            .then(response => {
                isLiked = response.data.is_liked;
                updateLikeUI();
            })
            .catch(err => console.log('检查点赞状态失败:', err));
    }
    
    // 更新点赞UI
    function updateLikeUI() {
        const likeBtn = document.getElementById('likeBtn');
        const likeIcon = document.getElementById('likeIcon');
        
        if (isLiked) {
            likeIcon.classList.remove('far');
            likeIcon.classList.add('fas');
            likeBtn.classList.add('active');
            likeIcon.style.color = '#ef4444';
        } else {
            likeIcon.classList.remove('fas');
            likeIcon.classList.add('far');
            likeBtn.classList.remove('active');
            likeIcon.style.color = '';
        }
    }
    
    // 切换点赞
    function toggleLike() {
        {% if not user.is_authenticated %}
        showError('请先登录');
        setTimeout(() => {
            window.location.href = '/users/login/?next={{ request.path }}';
        }, 1000);
        return;
        {% endif %}
        
        const endpoint = isLiked ? 'unlike' : 'like';
        
        axios.post(`/social/api/activities/${activityId}/${endpoint}/`)
            .then(response => {
                isLiked = !isLiked;
                updateLikeUI();
                
                // 更新点赞数
                const likeCount = document.getElementById('likeCount');
                const currentCount = parseInt(likeCount.textContent) || 0;
                likeCount.textContent = isLiked ? currentCount + 1 : currentCount - 1;
                
                showSuccess(isLiked ? '点赞成功' : '已取消点赞');
            })
            .catch(error => {
                console.error('点赞操作失败:', error);
                showError('操作失败，请重试');
            });
    }
    
    // 加载参与者
    function loadParticipants() {
        axios.get(`/api/activities/${activityId}/participants/`)
            .then(response => {
                const participants = response.data.results || response.data;
                const container = document.getElementById('participantsContainer');
                
                if (participants.length === 0) {
                    container.innerHTML = '<p class="text-muted text-center">还没有人报名</p>';
                } else {
                    container.innerHTML = participants.map(p => `
                        <div class="d-inline-block me-2 mb-2">
                            <img src="${p.user.avatar || '/static/img/default-avatar.png'}" 
                                 class="user-avatar" 
                                 data-bs-toggle="tooltip" 
                                 title="${p.user.nickname}">
                        </div>
                    `).join('');
                    
                    // 初始化tooltips
                    const tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
                    tooltips.forEach(t => new bootstrap.Tooltip(t));
                }
            })
            .catch(err => console.error('加载参与者失败:', err));
    }
    
    // 加载评论
    function loadComments() {
        API.comments.getList(activityId)
            .then(response => {
                const comments = response.data.results || response.data;
                document.getElementById('commentCount').textContent = comments.length;
                
                const container = document.getElementById('commentsContainer');
                if (comments.length === 0) {
                    container.innerHTML = '<p class="text-muted text-center py-4">暂无评论，快来抢沙发吧！</p>';
                } else {
                    container.innerHTML = comments.map(renderComment).join('');
                }
            })
            .catch(err => console.error('加载评论失败:', err));
    }
    
    // 渲染评论
    function renderComment(comment) {
        return `
            <div class="comment-item">
                <div class="comment-header">
                    <img src="${comment.user.avatar || '/static/img/default-avatar.png'}" class="user-avatar">
                    <div>
                        <div class="comment-author">${comment.user.nickname}</div>
                        <div class="comment-time">${formatDate(comment.created_at)}</div>
                    </div>
                    <div class="ms-auto">
                        <button class="btn btn-sm btn-link" onclick="likeComment(${comment.id})">
                            <i class="far fa-thumbs-up"></i> ${comment.like_count}
                        </button>
                    </div>
                </div>
                <div class="comment-content">${comment.content}</div>
            </div>
        `;
    }
    
    // 发表评论
    function submitComment() {
        const content = document.getElementById('commentInput').value.trim();
        if (!content) {
            showError('请输入评论内容');
            return;
        }
        
        API.comments.create(activityId, { content })
            .then(response => {
                showSuccess('评论发表成功');
                document.getElementById('commentInput').value = '';
                loadComments();
            })
            .catch(error => {
                showError('发表评论失败');
            });
    }
    
    // 点赞评论
    function likeComment(commentId) {
        API.comments.like(commentId)
            .then(response => {
                loadComments();
            })
            .catch(error => {
                showError('操作失败');
            });
    }
    
    // 检查报名状态
    function checkRegistrationStatus() {
        {% if user.is_authenticated and user.id != activity.creator.id %}
        axios.get(`/api/activities/${activityId}/registration-status/`)
            .then(response => {
                if (response.data.is_registered) {
                    const btn = document.getElementById('registerBtn');
                    btn.innerHTML = '<i class="fas fa-check"></i> 已报名';
                    btn.classList.remove('btn-gradient-success');
                    btn.classList.add('btn-secondary');
                    btn.disabled = true;
                }
            })
            .catch(err => console.error('检查报名状态失败:', err));
        {% endif %}
    }
    
    // 报名活动
    function registerActivity() {
        {% if activity.current_participants >= activity.max_participants %}
        showError('活动名额已满');
        return;
        {% endif %}
        
        const modal = new bootstrap.Modal(document.getElementById('registerModal'));
        modal.show();
    }
    
    // 确认报名
    function confirmRegistration() {
        const note = document.getElementById('registrationNote').value;
        
        API.activities.register(activityId, { note })
            .then(response => {
                showSuccess('报名成功！');
                bootstrap.Modal.getInstance(document.getElementById('registerModal')).hide();
                checkRegistrationStatus();
                loadParticipants();
            })
            .catch(error => {
                showError(error.response?.data?.message || '报名失败');
            });
    }
    
    // 分享活动
    function shareActivity() {
        if (navigator.share) {
            navigator.share({
                title: '{{ activity.title }}',
                text: '{{ activity.description|truncatewords:20 }}',
                url: window.location.href
            }).catch(err => console.log('分享失败:', err));
        } else {
            const url = window.location.href;
            navigator.clipboard.writeText(url).then(() => {
                showSuccess('链接已复制到剪贴板');
            });
        }
    }
    
    // 收藏活动
    function collectActivity() {
        showSuccess('收藏功能开发中...');
    }
    
    // 初始化地图
    function initMap() {
        const mapElement = document.getElementById('map');
        if (mapElement) {
            mapElement.innerHTML = `
                <div class="text-center py-5 bg-light rounded">
                    <i class="fas fa-map-marked-alt fa-3x text-muted mb-2"></i>
                    <p class="text-muted">地图功能需要接入第三方地图服务</p>
                    <p class="text-muted"><small>经纬度：{{ activity.latitude }}, {{ activity.longitude }}</small></p>
                </div>
            `;
        }
    }
    
    initMap();
</script>
{% endblock %}
